import React, { Component } from "react";
import "./05.css";

export default class ColorPicker extends Component {
  //声明状态
  state = {
    r: 0,
    g: 0,
    b: 0,
  };

  //声明方法
  save = (type) => {
    //返回事件回调函数
    return (e) => {
      //更新颜色的状态
      this.setState({
        [type]: e.target.value,
      });
    };
  };

  copy = async () => {
    let { r, g, b } = this.state;
    try {
      await navigator.clipboard.writeText(`rgb(${r},${g},${b})`);
      alert("复制成功");
    } catch (e) {
      alert('复制失败~~');
    }
  };
  render() {
    //解构赋值
    let { r, g, b } = this.state;
    return (
      <div className="color-container">
        {/* 颜色的显示区 */}
        <div
          className="color-show"
          style={{ background: `rgb(${r},${g},${b})` }}
        ></div>
        <hr />
        {/* 颜色的控制区 */}
        <div className="color-control">
          R:{" "}
          <input
            type="range"
            min="0"
            max="255"
            value={r}
            onChange={this.save("r")}
          />
          <span>{r}</span> <br />
          G:{" "}
          <input
            type="range"
            min="0"
            max="255"
            value={g}
            onChange={this.save("g")}
          />
          <span>{g}</span> <br />
          B:{" "}
          <input
            type="range"
            min="0"
            max="255"
            value={b}
            onChange={this.save("b")}
          />
          <span>{b}</span> <br />
          <input type="text" value={`rgb(${r},${g},${b})`} readOnly />
          <button onClick={this.copy}>点击复制</button>
        </div>
      </div>
    );
  }
}
